<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1200" @ok="handleSubmit">
    <div style="font-size:18px;color:#000;padding-left: 20px;height: 20px;">当前规则：{{rowObj.ruleName}}</div>
        <!-- <a-button type="primary" style="margin-bottom: 8px" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</a-button> -->
        <!-- <a-button type="primary" style="margin-bottom: 8px;margin-left:5px;" preIcon="ant-design:delete-outlined" @click="handleDel">删除</a-button> -->
        <!-- <a-table bordered :data-source="dataSource" :columns="columns" :row-selection="rowSelection" rowKey="key" >
            <template #bodyCell="{ column, text, record }">
            <template v-if="['weekDay'].includes(column.dataIndex)">
                <div class="editable-cell">
                <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                    <a-select
                        ref="select"
                        v-model:value="editableData[record.key][column.dataIndex]"
                        style="width: 120px"
                        >
                        <a-select-option :value="1" >星期一</a-select-option>
                        <a-select-option :value="2" >星期二</a-select-option>
                        <a-select-option :value="3" >星期三</a-select-option>
                        <a-select-option :value="4" >星期四</a-select-option>
                        <a-select-option :value="5" >星期五</a-select-option>
                        <a-select-option :value="6" >星期六</a-select-option>
                        <a-select-option :value="7" >星期日</a-select-option>
                    </a-select>
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ handleWeek[Number(text) ] || ' ' }}
                </div>
                </div>
            </template>
            <template v-if="['status'].includes(column.dataIndex)">
                <div class="editable-cell">
                <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                    <a-select
                        ref="select"
                        v-model:value="editableData[record.key][column.dataIndex]"
                        style="width: 120px"
                        >
                        <a-select-option value="1" >启用</a-select-option>
                        <a-select-option value="0" >停用</a-select-option>
                    </a-select>
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ handleStatus[Number(text) ] || ' ' }}
                </div>
                </div>
            </template>
            <template v-if="['startTime', 'endTime'].includes(column.dataIndex)">
                <div class="editable-cell">
                <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                    <a-time-picker v-model:value="editableData[record.key][column.dataIndex]" value-format="HH:mm:ss" format="HH:mm:ss"/>
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ text || ' ' }}
                </div>
                </div>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
                <div class="editable-row-operations">
                    <span v-if="editableData[record.key]">
                        <a-typography-link @click="handleSave(record.key)" style="margin-right:10px;">保存</a-typography-link>
                        <a-popconfirm title="确定取消吗" @confirm="cancel(record.key)">
                        <a>取消</a>
                        </a-popconfirm>
                    </span>
                    <span v-else>
                        <a @click="handleEdit(record.key)">编辑</a>
                    </span>
                </div>
            </template>
            </template>
        </a-table> -->
        <div class="timeArrBox" v-if="rowObj.ruleType=='w'">
            <div class="row" v-for="(item,index) in weekDataList" :key="index">
                <div class="weekBox" >{{handleWeek[item.weekday]}}</div>
                <div class="timeInputBox">
                    <div class="item" v-for="(item2,index2) in item.arrayTime" :key="index2">
                        <a-time-range-picker v-model:value="item2.time" value-format="HH:mm:ss"  />
                    </div>
                    <div class="action" @click="handleRowAddTime(index)">
                        新增
                    </div>
                </div>
            </div>
        </div>
        <div class="timeArrBox" v-else-if="rowObj.ruleType=='d'">
           <div class="row" v-for="(item,index) in dayDataList" :key="index">
                <div class="timeInputBox">
                    <div class="item" v-for="(item2,index2) in item.arrayTime" :key="index2">
                        <a-time-range-picker v-model:value="item2.time" value-format="HH:mm:ss"  />
                    </div>
                    <div class="action" @click="handleRowAddTime(index)">
                        新增
                    </div>
                </div>
            </div>
        </div>
  </BasicModal>
</template>

<script lang="ts" setup>

    import {ref, computed, unref,defineComponent ,reactive} from 'vue';
    import type { Ref, UnwrapRef } from 'vue';
    import { cloneDeep } from 'lodash-es';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../AcRule.data';
    import { message } from 'ant-design-vue';
    import type { TableProps, } from 'ant-design-vue';
    import {saveOrUpdate,ruleListApi,addRuleApi,editRuleApi,delRuleApi} from '../AcRule.api';
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    let pageNo = ref(1)
    let pageSize = ref(10)
    let total = ref(0)
    const count = computed(() => dataSource.value.length + 1)
    let columns = ref([  {
        title: '周几',
        dataIndex: 'weekDay',
        width: '20%',
      },
       {
        title: '状态',
        dataIndex: 'status',
        width: '20%',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        width: '20%',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        width: '20%',
      },
      {
        title: '操作',
        dataIndex: 'operation',
      }]);
    let dayDataList = ref([
        {
            weekday: 0,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time:[]
            }]
        }
    ])
    let weekDataList = ref([
        {
            weekday: 1,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time:[]
            }]
        },
        {
            weekday: 2,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time: []
            }]
        },
         {
            weekday: 3,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time: []
            }]
        },
         {
            weekday: 4,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time:[]
            }]
        },
         {
            weekday: 5,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time: []
            }]
        },
         {
            weekday: 6,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time: []
            }]
        },
         {
            weekday: 7,
            arrayTime:[{
                startTime:'',
                endTime : '',
                time: []
            }]
        },
    ])
    //表单赋值
    let rowObj = ref({});
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
      
        // await resetFields();

       
        //重置表单
        // setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        // isUpdate.value = !!data?.isUpdate;
        // if (unref(isUpdate)) {
        //     //表单赋值
        //     await setFieldsValue({
        //         ...data.record,
        //     });
        // }
        // 隐藏底部时禁用整个表单
    //    setProps({ disabled: !data?.showFooter })
        console.log(data.record);
        console.log(111);
        rowObj.value = data.record
        // clearReactiveState(editableData)
        // if(rowObj.value.ruleType=='d' && columns.value.length==5){
        //     columns.value.splice(0,1)
        // }else if(rowObj.value.ruleType=='w' && columns.value.length==4){
        //     columns.value.unshift({
        //         title: '周几',
        //         dataIndex: 'weekDay',
        //         width: '20%',
        //     })
        // }
       getRuleList()
    });
    function handleRowAddTime(index){
        if(rowObj.value.ruleType=='d'){
             if(dayDataList.value[index].arrayTime.length==8) return message.error('最多设置8个时间段')
                dayDataList.value[index].arrayTime.push({
                        startTime:'',
                        endTime : '',
                        time: []
                })
        }else if(rowObj.value.ruleType=='w'){
             if(weekDataList.value[index].arrayTime.length==8) return message.error('最多设置8个时间段')
                weekDataList.value[index].arrayTime.push({
                        startTime:'',
                        endTime : '',
                        time: []
                })
        }
       
    }
    const getRuleList= () =>{
        ruleListApi({
            ruleId : rowObj.value.id,
            // pageNo : pageNo.value,
            // pageSize: pageSize.value
        }).then(res=>{
            console.log(res);
            dayDataList.value[0].arrayTime = [{
                startTime:'',
                endTime : '',
                time:[]
            }]

            weekDataList.value.forEach(item=>{
                item.arrayTime = [{
                    startTime:'',
                    endTime : '',
                    time:[]
                }]
            })
            if(rowObj.value.ruleType=='d'){
                res.forEach(item=>{
                    item.arrayTime.forEach(item2=>{
                        item2.time = []
                        item2.time[0] = item2.startTime
                        item2.time[1] = item2.endTime
                    })
                    dayDataList.value[0].arrayTime = item.arrayTime
                })
            }else if(rowObj.value.ruleType=='w'){
                res.forEach(item=>{
                    item.arrayTime.forEach(item2=>{
                        item2.time = []
                        item2.time[0] = item2.startTime
                        item2.time[1] = item2.endTime
                    })
                    weekDataList.value[item.weekday-1].arrayTime = item.arrayTime
                })
            }
            // res.records.forEach((item,index)=>{
            //     item.key = index
            // })
            // dataSource.value = res.records 
            // total.value = res.total 
        })
    }
    const pageSizeChange = (page,pageSize)=>{
       pageNo.value = page
       getRuleList()
    }
    // let  pagination =ref( {
    //     // 分页配置
    //     pageSize, // 每页显示的条数
    //     // showSizeChanger: true, // 是否可以改变每页显示的条数
    //     showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
    //     current: 1, // 当前页数
    //     total, // 总条数
    //     onChange: (page,pageSize)=>{
    //         pageNo.value = page
    //         getRuleList()
    //     } // 页码改变时的回调函数
    // })


    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '设置时段' : '设置时段'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let data = []
            if(rowObj.value.ruleType=='d'){
                dayDataList.value.forEach(item=>{
                    item.ruleId = rowObj.value.id
                    item.arrayTime.forEach(item2=>{
                        if(item2.time && item2.time.length != 0){
                            item2.startTime = item2.time[0]
                            item2.endTime = item2.time[1]
                        }else{
                            item2.startTime = ''
                            item2.endTime = ''
                        }

                    })
                })
                data = dayDataList.value
            }else if(rowObj.value.ruleType=='w'){
                weekDataList.value.forEach(item=>{
                    item.ruleId = rowObj.value.id
                    item.arrayTime.forEach(item2=>{
                        if(item2.time && item2.time.length != 0){
                            item2.startTime = item2.time[0]
                            item2.endTime = item2.time[1]
                        }else{
                            item2.startTime = ''
                            item2.endTime = ''
                        }
                    })
                })
                data = weekDataList.value
            }
            


            setModalProps({confirmLoading: true});

            await addRuleApi( data
                // [{
                // ruleId: rowObj.value.id,
                // weekday: data
                // }]
            )
            // let values = await validate();
            // return
            // setModalProps({confirmLoading: true});
            // //提交表单
            // // await saveOrUpdate(values, isUpdate.value);
            // await  addRuleApi(dataSource.value)

            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    
    let dataSource = ref([]);
   
    const editableData = reactive({});
    let selectedRowsArr = reactive([]);
    const rowSelection: TableProps['rowSelection'] = {
      onChange: (selectedRowKeys: string[], selectedRows: any[]) => {
        selectedRowsArr.value = selectedRows
        console.log(selectedRowsArr);
      },
    };
    const handleEdit = (key: string) => {
      editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
    };
    const cancel = (key: string) => {
      delete editableData[key];
    };
    const handleSave = (key: string) => {
      Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
      console.log(editableData[key]);
      let tempObj = editableData[key]
    //   tempObj.ruleId = rowObj.id
    //   if(tempObj.id){
    //     editRuleApi(tempObj)
    //   }else{
    //      // 新增
    //     addRuleApi(
    //         tempObj
    //     ).then(res=>{
    //     })
    //   }
     
      delete editableData[key];
    };

    const onDelete = (id: string) => {
      dataSource.value = dataSource.value.filter(item => item.id !== id);
    };
    const handleAdd = () => {
        let keyArr = Object.keys(editableData)
        console.log(keyArr);
        if(keyArr.length != 0 ) return message.warning('请先保存编辑数据');

        // let tempData = dataSource.value.filter(item => item.id=='');
        // if(tempData.length != 0 ) return message.warning('请先编辑刚新增的数据');

        const newData = {
            key: count.value,
            id: '',
            weekDay: 1,
            status: '1',
            startTime: '00:00:00',
            endTime: '00:00:00',
            ruleId : rowObj.value.id,
        };  
        dataSource.value.push(newData);
    };
    const handleDel = () => {
        if(selectedRowsArr.value.length == 0 ) return message.warning('请先选择需要删除的数据');
        let tempData = selectedRowsArr.value.filter(item => item.id=='');
        if(tempData.length != 0 ) return message.warning('该数据需编辑保存后才能删除');
        let ids = []
        selectedRowsArr.value.forEach(item => ids.push(item.id))
        let idsStr = ids.join(',')
        delRuleApi(
            {ids:idsStr}
        ).then(res=>{
            getRuleList()
        })
    }
    let handleWeek = ref(['星期','星期一','星期二','星期三','星期四','星期五','星期六','星期日'])
    let handleStatus = ['停用','启用',]
    // 清空响应式对象
    function clearReactiveState(reactiveObject) {
    // 使用空对象重置响应式对象
    for (const key in reactiveObject) {
        if (Object.hasOwnProperty.call(reactiveObject, key)) {
        delete reactiveObject[key];
        }
    }
    }
</script>

<style lang="less" scoped>
.tableHiddle {
  display: none;
}
.tableShow{
  display: revert;
}
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
    .timeArrBox{
        margin: 20px;
        border-bottom: 1px solid #f0f0f0;
        overflow: auto;
        .row{
            display: flex;
            border-top: 1px solid #f0f0f0;
            border-left: 1px solid #f0f0f0;
            border-right: 1px solid #f0f0f0;
            .weekBox{
                padding: 20px;
                width: 200px;
                text-align: center;
                color: #000;
            }
            .timeInputBox{
                flex: 1;
                border-left: 1px solid #f0f0f0;
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                padding: 5px 10px;
                .item{
                    margin: 5px 10px;
                    width: 190px;
                }
                .action{
                    margin: 0 40px;
                    text-align: center;
                    color: #1890ff;
                    cursor: pointer;
                }
            }
        }
    }  
</style>